<?php


namespace app\jun\controller;

use app\erp\model\Attrdb;
use app\erp\model\Baojiadb;
use app\erp\model\BottomPriceLogdb;
use app\erp\model\Buildtpldb;
use app\erp\model\Cartdb;
use app\erp\model\Goodsdb;
use app\erp\model\GoodsPriceLogdb;
use app\erp\model\OrderApplyEinvoicedb;
use app\erp\model\Orderdb;
use app\erp\model\OrderLogdb;
use app\erp\model\PushBottomPricedb;
use app\erp\model\SalePricedb;
use app\erp\model\Shoppingdb;
use app\erp\model\TljLogdb;
use app\erp\model\TljMsgdb;
use app\erp\model\UCartdb;
use app\erp\model\UGoodsdb;
use app\erp\model\UOrderApplyEinvoicedb;
use app\erp\model\UOrderdb;
use app\erp\model\Uploaddb;
use think\Controller;
use think\Db;
use think\Exception;

class Tljapis extends Controller
{
    protected $member_id = 0;
    protected $param;
    protected $com = [
        '自配物流',
        '圆通速递',
        '韵达快递',
        '申通快递',
        '中通快递',
        '顺丰速运',
        'EMS',
        '京东物流',
        '邮政标准快递',
        '德邦快递',
        '德邦',
        '百世快递',
        '中通快运',
        '韵达快运',
        '京东快运',
        '百世快运',
        '丰网速运',
        '宅急送',
        '顺丰快运',
        '安能快运',
        '速必达',
        '天天快递',
        '极兔速递',
        '日日顺物流',
        '丹鸟',
        '袋鼠速递'
    ];

    public function _initialize()
    {
        header("Access-Control-Allow-Origin: *");
        header('Content-Type:application/json; charset=utf-8');
        $this->param = $this->request->param();
        if (!defined('SITE_ID')) {
            define('SITE_ID', 117);
        }
        if (!defined('PARTNER_ID')) {
            define('PARTNER_ID', 25);
        }
        $this->checkToken();
    }

    // 保存日志
    protected function saveLog($return_msg)
    {
        $tljLogdb = new TljLogdb();
        $tljLogdb->save([
            'log_url' => $this->request->action(),
            'member_id' => $this->member_id,
            'log_param' => json_encode($this->request->param()),
            'create_time' => date('Y-m-d H:i:s'),
            'return_msg' => $return_msg
        ]);
        return $tljLogdb->id;
    }

    // 校验token
    protected function checkToken()
    {
        if (!$this->request->isPost()) {
            $this->apiError('请使用POST方式提交');
        }
        if (!in_array(strtolower($this->request->action()), ['gettoken', 'syncbottomprice', 'pushjunprice'])) {
            if (!isset($this->param['token'])) {
                $this->apiError('token为空');
            }
            $memberdb = new \app\erp\model\Memberdb();
            $get_member = $memberdb->where('token', $this->param['token'])->find();
            if ($get_member) {
                if (!defined('MEMBER_ID')) {
                    define('MEMBER_ID', $get_member['member_id']);
                }
                $this->member_id = $get_member['member_id'];
                if ($get_member['expires_time'] < time()) {
                    $this->apiError('token已失效');
                }
            } else {
                $this->apiError('token错误');
            }
        }

    }

    /**
     * Title("同步军网最低价,军网采集的数据")
     */
    public function syncBottomPrice()
    {
        try {
            session('member_id', 1);
            $user_info = array('appkey' => 'e8ilqbk9zfwlvcc9', 'appsecret' => '1qcrlz9t1xtudnlxc0b5jxgtpey47sdmxvcmx3hjaqi7axhl');
            if (!isset($this->param['appkey'])) {
                $this->apiError('secret为空');
            }
            if (!isset($this->param['appsecret'])) {
                $this->apiError('secret为空');
            }
            if ($this->param['appkey'] != $user_info['appkey']) {
                $this->apiError('appkey错误');
            }
            if ($this->param['appsecret'] != $user_info['appsecret']) {
                $this->apiError('secret错误');
            }
            if (!isset($this->param['goods'])) {
                $this->apiError('底价数据错误:001');
            }
            if (!is_array($this->param['goods'])) {
                $this->apiError('底价数据错误:002');
            }
            if (count($this->param['goods']) == 0) {
                $this->apiError('底价数据错误:003');
            }
            $save_data = [];
            $price_data = [];
            $sale_price_data = [];
            $price_log_data = [];
            foreach ($this->param['goods'] as $key => $val) {
                if (!isset($val['goods_sku'])) {
                    $this->apiError('底价商品错误');
                }
                if (!isset($val['bottom_price'])) {
                    $this->apiError('底价错误');
                }
                $temp = [];
                $temp['goods_sku'] = $val['goods_sku'];
                $temp['bottom_price'] = $val['bottom_price'] == '暂无报价' ? 0 : $val['bottom_price'];
                $temp['bottom_date'] = date('Y-m-d H:i:s');
                $get_sale_price = Db::name('sale_price')->where('goods_sku', $val['goods_sku'])->field('sale_price_id,api_price,jun_zuidijia,zuidijia,sale_price,view_stock,caigoujia,chengbenjia,beizhu')->order('sale_price_id desc')->find();
                $temp['old_sale_price'] = $get_sale_price['sale_price'];
                $temp['old_api_price'] = $get_sale_price['api_price'];
                $temp['old_view_stock'] = $get_sale_price['view_stock'];
                $temp['old_caigoujia'] = $get_sale_price['caigoujia'];
                $temp['old_chengbenjia'] = $get_sale_price['chengbenjia'];
                $temp['old_beizhu'] = $get_sale_price['beizhu'];
                $temp['old_jun_zuidijia'] = $get_sale_price['jun_zuidijia'];
                $temp['old_zuidijia'] = $get_sale_price['zuidijia'];
                array_push($save_data, $temp);
                if ($get_sale_price && $get_sale_price['zuidijia'] != $val['bottom_price']) {
                    if (stripos($get_sale_price['beizhu'], '保持最低价') === 0) {
                        array_push($price_data, array('productguid' => $val['goods_sku'], 'indicativeprice' => $get_sale_price['sale_price'], 'lowprice' => $temp['bottom_price'], 'create_date' => date('Y-m-d H:i:s')));
                    }
                    // 如果使用定时器 zuidijia这个值有定时器执行
                    //array_push($sale_price_data, array('sale_price_id' => $get_sale_price['sale_price_id'], 'jun_zuidijia' => $val['bottom_price'], 'zuidijia' => $val['bottom_price']));
                    array_push($sale_price_data, array('sale_price_id' => $get_sale_price['sale_price_id'], 'jun_zuidijia' => $val['bottom_price']));
                    //array_push($sale_price_data, array('sale_price_id' => $get_sale_price['sale_price_id'], 'jun_zuidijia' => $val['bottom_price'], 'push_state' => $val['caigoujia'] == 0 ? 1 : 0));
                }
                // 商品价格日志开始
                $temp_log = [];
                $temp_log['goods_sku'] = $val['goods_sku'];
                $temp_log['date'] = date('Y-m-d H:i:s');
                $temp_log['types'] = '推送最低价';
                $temp_log_son = [];
                $temp_log_son['参考价'] = $get_sale_price['sale_price'];
                $temp_log_son['报价'] = $get_sale_price['api_price'];
                $temp_log_son['当前最低价'] = $get_sale_price['zuidijia'];
                $temp_log_son['推送最低价'] = $val['bottom_price'] == '暂无报价' ? 0 : $val['bottom_price'];
                $temp_log_son['用户'] = '最低价接口';
                $temp_log['params'] = json_encode($temp_log_son, JSON_UNESCAPED_UNICODE);
                array_push($price_log_data, $temp_log);
                // 商品价格日志结束
            }

            if (count($price_data)) {

                // 实时推送
                /*$goodsApi = new \app\erp\controller\Goods();
                $goodsApi->commMinPrice($price_data);*/

                // 定时推送
                $pushBottomPricedb = new PushBottomPricedb();
                $pushBottomPricedb->saveAll($price_data);

                // 保存最低价
                $salePricedb = new SalePricedb();
                $salePricedb->saveAll($sale_price_data);
            }
            $bottomPriceLogdb = new BottomPriceLogdb();
            $bottomPriceLogdb->saveAll($save_data);

            $goodsPriceLogdb = new GoodsPriceLogdb();
            $goodsPriceLogdb->saveAll($price_log_data);

            $this->apiSuccess(array('msg' => '同步成功'));
        } catch (Exception $e) {
            $this->apiError($e->getMessage());
        }

    }

    /**
     * Title("推送报价")
     */
    public function pushJunPrice()
    {
        session('member_id', 1);
        $user_info = array('appkey' => 'e8ilqbk9zfwlvcc9', 'appsecret' => '1qcrlz9t1xtudnlxc0b5jxgtpey47sdmxvcmx3hjaqi7axhl');
        if (!isset($this->param['appkey'])) {
            $this->apiError('secret为空');
        }
        if (!isset($this->param['appsecret'])) {
            $this->apiError('secret为空');
        }
        if ($this->param['appkey'] != $user_info['appkey']) {
            $this->apiError('appkey错误');
        }
        if ($this->param['appsecret'] != $user_info['appsecret']) {
            $this->apiError('secret错误');
        }
        if (!isset($this->param['goods'])) {
            $this->apiError('报价数据错误:001');
        }
        if (!is_array($this->param['goods'])) {
            $this->apiError('报价数据错误:002');
        }
        if (count($this->param['goods']) == 0) {
            $this->apiError('报价数据错误:003');
        }
        if (count($this->param['goods']) > 100) {
            $this->apiError('一次性报价不能超过100条');
        }
        $save_data = [];
        $price_data = [];
        $sale_price_data = [];
        foreach ($this->param['goods'] as $key => $val) {
            if (!isset($val['goods_sku'])) {
                $this->apiError('报价商品错误');
            }
            if (!isset($val['api_price'])) {
                $this->apiError('报价错误');
            }
            if (!isset($val['stock'])) {
                $this->apiError('报价库存错误');
            }
            $temp = [];
            $temp['goods_sku'] = $val['goods_sku'];
            $temp['api_price'] = $val['api_price'] == '暂无报价' ? 0 : $val['api_price'];
            $temp['bottom_date'] = date('Y-m-d H:i:s');
            $temp['stock'] = $val['stock'];
            $get_sale_price = Db::name('sale_price')->where('goods_sku', $val['goods_sku'])->field('sale_price_id,api_price,jun_zuidijia,zuidijia,sale_price,view_stock,caigoujia,chengbenjia,beizhu')->order('sale_price_id desc')->find();
            $temp['old_sale_price'] = $get_sale_price['sale_price'];
            $temp['old_api_price'] = $get_sale_price['api_price'];
            $temp['old_view_stock'] = $get_sale_price['view_stock'];
            $temp['old_caigoujia'] = $get_sale_price['caigoujia'];
            $temp['old_chengbenjia'] = $get_sale_price['chengbenjia'];
            $temp['old_beizhu'] = $get_sale_price['beizhu'];
            $temp['old_jun_zuidijia'] = $get_sale_price['jun_zuidijia'];
            $temp['old_zuidijia'] = $get_sale_price['zuidijia'];
            array_push($save_data, $temp);
            if ($get_sale_price) {
                $t = [];
                $t ['sku'] = $val['goods_sku'];
                $t ['price'] = $val['api_price'];
                $t ['stock'] = $val['stock'];
                $goods_id = Db::name('goods')->where('goods_sku', $val['goods_sku'])->value('goods_id');
                $t ['linkurl'] = 'http://tailongjipc.dixintong.com/goods_detail.html?goods_sku=' . $goods_id;
                $t ['eccode'] = $goods_id;
                $t ['linkprice'] = $get_sale_price['sale_price'];
                $t ['min_price'] = $get_sale_price['jun_zuidijia'];
                $t ['indicativeprice'] = $get_sale_price['sale_price'];
                array_push($price_data, $t);
                array_push($sale_price_data, array('sale_price_id' => $get_sale_price['sale_price_id'], 'api_price' => $val['api_price'], 'view_stock' => $val['stock']));
            }
        }

        if (count($price_data)) {
            // 实时推送
            $goodsApi = new \app\erp\controller\Goods();
            $goodsApi->pushJunPriceExcel($price_data);

            // 保存最低价
            $salePricedb = new SalePricedb();
            $salePricedb->saveAll($sale_price_data);
        }
        $bottomPriceLogdb = new BottomPriceLogdb();
        $bottomPriceLogdb->saveAll($save_data);
        $this->apiSuccess(array('msg' => '同步成功'));
    }

    public function index()
    {
        exit ('欢迎使用');
    }

    protected function ajaxReturn($return, $json_option = 0)
    {
        header('Content-Type:application/json; charset=utf-8');
        $return['log_id'] = $this->saveLog(json_encode($return, $json_option));
        exit (json_encode($return, $json_option));
    }

    // 成功返回值
    public function apiSuccess($data)
    {
        $return['data'] = $data;
        $return ['returnMsg'] = 'success';
        $return ['isSuccess'] = true;
        $this->ajaxReturn($return);
    }

    // 失败返回值
    public function apiError($msg)
    {
        $return ['isSuccess'] = false;
        $return ['returnMsg'] = $msg;
        $this->ajaxReturn($return);
    }

    /**
     * @Title("获取token")
     * @param ("appkey")
     * @param ("appsecret")
     */
    public function getToken()
    {
        if (!isset($this->param['appkey'])) {
            $this->apiError('appkey错误');
        }
        if (!isset($this->param['appsecret'])) {
            $this->apiError('secret为空');
        }
        $memberdb = new \app\erp\model\Memberdb();
        $get_member = $memberdb
            ->where('appkey', $this->param['appkey'])
            ->where('appsecret', $this->param['appsecret'])
            ->find();
        if ($get_member) {
            $this->member_id = $get_member['member_id'];
            if (intval($get_member['expires_time']) > 0 && $get_member['expires_time'] > time()) {
                $result['token'] = $get_member['token'];
                $result['expires_time'] = $get_member['expires_time'];
            } else {
                $result['token'] = md5($this->param['appkey'] . $this->param['appsecret'] . time());
                $result['expires_time'] = time() + 7200;
                $get_member->save($result);
            }
            $this->apiSuccess($result);
        } else {
            $this->apiError('获取token错误');
        }
    }

    /**
     * @Title("获取商品分类")
     * @param("token","必填")
     * @param("category_name","分类名称，可选")
     */
    public function goodsCategory()
    {
        $categorydb = new \app\erp\model\Categorydb();
        if (isset($this->param['category_name']) && $this->param['category_name']) {
            $categorydb->param['category_name'] = $this->param['category_name'];
        }
        $get_category = $categorydb->where('site_id', 117)
            ->where('level', 3)
            ->where('audit_state', 1)
            ->field('category_name,category_sign as category_id')
            ->select();
        $this->apiSuccess($get_category);
    }

    /**
     * Title("商品SKU")
     * @param("token","必填")
     * @param("category_id","商品分类ID")
     */
    public function goodsSku()
    {
        $goodsdb = new \app\erp\model\Goodsdb();
        $get_goods = $goodsdb
            ->where('category_sign3', $this->param['category_id'])
            /*->where('sale_state', 1)
            ->where('audit_state', 1)
            ->where('junsale_state', 1)*/
            ->column('goods_sku');
        $this->apiSuccess($get_goods);
    }

    /**
     * Title("商品详情")
     * @param ("token","必填")
     * @param ("goods_sku","必填")
     */
    public function skuDetail()
    {
        if (!isset($this->param['goods_sku'])) {
            $this->apiError('sku错误');
        }
        $goodsdb = new \app\erp\model\Goodsdb();
        $get_goods = $goodsdb->where('goods_sku', $this->param['goods_sku'])
            /*->where('sale_state', 1)
            ->where('audit_state', 1)
            ->where('junsale_state', 1)*/
            ->field('goods_sku,goods_name,goods_unit,goods_model,goods_content,category_sign3 category_id,brand_sign brand_id,goods_picture,check_area,is_lock,sale_state,api_option')
            ->find();
        if ($get_goods) {
            $get_goods->append(['goods_image', 'category_name', 'brand_name'])->hidden(['api_option']);
            //$get_goods['attr'] = $this->skuAttr($get_goods['category_sign']);
            $this->apiSuccess($get_goods);
        } else {
            $this->apiError('sku未找到');
        }
    }

    /**
     * Title("多商品详情")
     * @param ("token","必填")
     * @param ("goods_sku_arr","商品SKU数组 必填，最多100条")
     */
    public function skuDetails()
    {
        if (!isset($this->param['goods_sku_arr'])) {
            $this->apiError('sku错误');
        }
        if (!is_array($this->param['goods_sku_arr'])) {
            $this->apiError('sku不是数组');
        }
        if (count($this->param['goods_sku_arr']) > 100) {
            $this->apiError('每次请求不能超过100条');
        }
        $goodsdb = new \app\erp\model\Goodsdb();
        $get_goods = $goodsdb->whereIn('goods_sku', implode(',', $this->param['goods_sku_arr']))
            /*->where('sale_state', 1)
            ->where('audit_state', 1)
            ->where('junsale_state', 1)*/
            ->field('goods_sku,goods_name,goods_unit,goods_model,goods_content,category_sign3 category_id,brand_sign brand_id,goods_picture,check_area,is_lock,api_option')
            ->select();
        if ($get_goods) {
            $get_goods->append(['goods_image', 'category_name', 'brand_name'])->hidden(['api_option']);
            //$get_goods['attr'] = $this->skuAttr($get_goods['category_sign']);
            $this->apiSuccess($get_goods);
        } else {
            $this->apiError('sku未找到');
        }
    }

    /**
     * Title("获取商品最低价和锁定状态")
     * @param("token","必填")
     * @param("goods_sku_arr","sku数组，必填")
     */
    public function goodsBottomPrice()
    {
        if (!isset($this->param['goods_sku_arr'])) {
            $this->apiError('sku错误');
        }
        if (!is_array($this->param['goods_sku_arr'])) {
            $this->apiError('sku不是数组');
        }
        if (count($this->param['goods_sku_arr']) > 100) {
            $this->apiError('每次请求不能超过100条');
        }
        $get_goods = Db::name('goods')->alias('goods')
            ->join('sale_price price', 'goods.goods_sku = price.goods_sku')
            ->field('goods.goods_sku,goods.is_lock,price.zuidijia bottom_price')
            ->whereIn('goods.goods_sku', $this->param['goods_sku_arr'])
            ->where('sale_state', 1)
            ->where('audit_state', 1)
            ->where('junsale_state', 1)
            ->select();
        $this->apiSuccess($get_goods);
    }

    // 商品属性
    protected function skuAttr($category_sign, $goods_sku)
    {
        $attr = Db::name('attr')->alias('attr')
            //->fetchSql(true)
            ->join('attr_value val', 'attr.attr_sign=val.attr_sign')
            ->where('attr.category_sign', $category_sign)
            ->where('val.goods_sku', $goods_sku)
            ->order('sort asc,group_name asc,attr_id asc')
            ->field('attr.attr_name paramname,val.attr_value paramvalue')
            ->select();
        return $attr;
    }

    /**
     * Title("商品属性")
     * @param("token","必填")
     * @param("goods_sku","必填")
     */
    public function goodsAttr()
    {
        if (!isset($this->param['goods_sku'])) {
            $this->apiError('sku错误');
        }
        $category_sign = Db::name('goods')->where('goods_sku', $this->param['goods_sku'])
            ->where('sale_state', 1)
            ->where('audit_state', 1)
            ->where('junsale_state', 1)
            ->field('category_sign3 category_sign,goods_sku,api_option')
            ->find();
        if ($category_sign) {
            $attr['goods_sku'] = $this->param['goods_sku'];
            if (strpos($category_sign['goods_sku'], 'SKU') === false) {
                $option = json_decode($category_sign['api_option'], true);
                $attr['attr'] = $option['param'];
            } else {
                $attr['attr'] = $this->skuAttr($category_sign['category_sign'], $category_sign['goods_sku']);
            }
            $this->apiSuccess($attr);
        } else {
            $this->apiError('sku未找到');
        }
    }


    /**
     * Title("商品价格")
     * @param("token","必填")
     * @param("goods_sku","必填")
     */
    public function goodsPrice()
    {
        if (!isset($this->param['goods_sku'])) {
            $this->apiError('sku错误');
        }
        $goods = Db::name('goods')->where('goods_sku', $this->param['goods_sku'])
            ->where('sale_state', 1)
            ->where('audit_state', 1)
            ->where('junsale_state', 1)
            ->count();
        if ($goods == 1) {
            $price = Db::name('sale_price')->where('goods_sku', $this->param['goods_sku'])
                ->order('sale_price_id desc')
                ->field('goods_sku,market_price,zuidijia bottom_price')
                ->find();
            $this->apiSuccess($price);
        } else {
            $this->apiError('sku未找到');
        }
    }

    /**
     * Title("商品库存")
     * @param("token","必填")
     * @param("goods_sku","必填")
     */
    public function goodsStock()
    {
        if (!isset($this->param['goods_sku'])) {
            $this->apiError('sku错误');
        }
        $goods = Db::name('goods')->where('goods_sku', $this->param['goods_sku'])
            ->where('sale_state', 1)
            ->where('audit_state', 1)
            ->where('junsale_state', 1)
            ->count();
        if ($goods == 1) {
            $price = Db::name('sale_price')->where('goods_sku', $this->param['goods_sku'])
                ->order('sale_price_id desc')
                ->field('goods_sku,view_stock stock')
                ->find();
            $this->apiSuccess($price);
        } else {
            $this->apiError('sku未找到');
        }
    }

    /**
     * Title("订单信息")
     * @param("token","必填")
     * @param("order_no","订单号，必填")
     */
    public function orderDetail()
    {
        if (!isset($this->param['order_no'])) {
            $this->apiError('订单号错误');
        }
        $order_info = Db::name('order')
            ->where('out_order_no', $this->param['order_no'])
            ->field('out_order_no order_no,order_no old_order_no,order_money,api_param,supplier_id,create_time,shopping_id')
            ->find();
        if ($order_info) {
            if ($order_info['supplier_id'] != $this->member_id) {
                $this->apiError('无订单权限');
            }
            $result = [];
            $param = json_decode($order_info['api_param'], true);

            $result['order_no'] = $order_info['order_no'];
            $result['create_time'] = $order_info['create_time'];
            $result['order_money'] = $order_info['order_money'] / 100;
            $result['freight'] = $param['freight'] ?? '';
            $result['remark'] = $param['remark'];
            $result['contact'] = $param['name'];
            $result['address']['city_name'] = $param['Cityname'];
            $result['email'] = $param['email'] ?? '';
            $result['address']['street'] = $param['address'];
            if (isset($param['provinceId'])) {
                $result['phone'] = $param['phone'] ?: $param['mobile'];
                $result['address']['province_id'] = $param['provinceId'];
                $result['address']['city_id'] = $param['cityId'];
                $result['address']['county_id'] = $param['countyId'];
                $result['address']['town_id'] = $param['townId'];
                $result['invoice']['invoice_type'] = $param['invoiceType'];
                $result['invoice']['invoice_content'] = $param['invoiceContent'];
            } else {
                $shoppingdb = new Shoppingdb();
                $get_shopping = (array)$shoppingdb->ajaxFind($order_info['shopping_id']);
                if ($get_shopping) {
                    $result['phone'] = $get_shopping['phone'];
                    $result['address']['province_id'] = $get_shopping['province'];
                    $result['address']['city_id'] = $get_shopping['city'];
                    $result['address']['county_id'] = $get_shopping['area'];
                }
                $result['address']['town_id'] = '';
                $result['invoice']['invoice_type'] = 1;
                $result['invoice']['invoice_content'] = '';
            }

            $result['invoice']['company_name'] = $param['companyName'];
            $result['invoice']['invoice_tax_no'] = $param['invoiceTaxNo'];

            $result['invoice']['danweiguid'] = $param['danweiguid'];
            $result['goods'] = [];
            /*if (isset($param['provinceId'])) {
                foreach ($param['sku'] as $key => $val) {
                    $temp['goods_sku'] = $val['skuId'];
                    $temp['buy_num'] = $val['num'];
                    $temp['price'] = $val['price'];
                    array_push($result['goods'], $temp);
                }
            } else {
                $result['goods'] = Db::name('cart')->where('order_no', $order_info['old_order_no'])->field('goods_sku,goods_num buy_num,goods_sale_price price')->select();
            }*/
            $result['goods'] = Db::name('cart')->where('order_no', $order_info['old_order_no'])->field('goods_sku,goods_num buy_num,goods_sale_price price')->select();

            $this->apiSuccess($result);
        } else {
            $this->apiError('未找到订单号');
        }
    }

    /**
     * Title("订单状态")
     * @param("token","必填")
     * @param ("order_no","订单号，必填")
     */
    public function orderState()
    {
        if (!isset($this->param['order_no'])) {
            $this->apiError('订单号错误');
        }
        $order_info = Db::name('order')
            ->where('out_order_no', $this->param['order_no'])
            ->field('out_order_no order_no,supplier_id,order_state,gys_fh_state,gys_sh_state,gys_fh_time,gys_sh_time')
            ->find();
        if ($order_info) {
            if ($order_info['supplier_id'] != $this->member_id) {
                $this->apiError('无订单权限');
            }
            $result = [];
            $result['order_no'] = $order_info['order_no'];
            $result['order_state'] = $order_info['order_state'];
            $result['supplier_deliver_state'] = $order_info['gys_fh_state'];
            $result['supplier_deliver_time'] = $order_info['gys_fh_time'];
            $result['supplier_receipt_state'] = $order_info['gys_sh_state'];
            $result['supplier_receipt_time'] = $order_info['gys_sh_time'];
            $this->apiSuccess($result);
        } else {
            $this->apiError('未找到订单号');
        }
    }

    /**
     * Title("申请取消订单")
     * @param("token","必填")
     * @param ("order_no","订单号，必填")
     * @param ("reason",“废止原因，必填”)
     * @param("files","废止凭证")
     */
    public function applyStopOrder()
    {
        if (!isset($this->param['order_no'])) {
            $this->apiError('订单号错误');
        }
        if (!isset($this->param['reason']) || !$this->param['reason']) {
            $this->apiError("废止原因错误");
        }
        if (!isset($this->param['files'])) {
            $this->apiError("废止凭证错误");
        }
        $order_info = Db::name('order')
            ->where('out_order_no', $this->param['order_no'])
            ->field('order_id,out_order_no order_no,supplier_id,order_state')
            ->find();
        if ($order_info) {
            if ($order_info['supplier_id'] != $this->member_id) {
                $this->apiError('无订单权限');
            }
            if (!in_array($order_info['order_state'], [3, 4, 5])) {
                $save_data['reason'] = $this->param['reason'];
                $save_data['files'] = $this->param['files'] ?: '';
                $save_data['order_no'] = $order_info['order_no'];
                $junApi = new Api();
                $result = [];
                $result['apply_state'] = $junApi->apiApplyStopOrder($save_data);
                $result['order_no'] = $order_info['order_no'];
                $this->apiSuccess($result);
            } else {
                $this->apiError('订单已发货，不能取消订单');
            }
        } else {
            $this->apiError('未找到订单号');
        }
    }

    /**
     * Title("获取物流公司信息")
     * @param("token","必填")
     */
    public function getLogistics()
    {

        $this->apiSuccess($this->com);
    }

    /**
     * Title("获取物流公司信息新版")
     * @param("token","必填")
     * @param("com_name","物流公司名称搜索，非必填")
     * @param("com_id","物流公司编号搜索，非必填")
     */
    public function getLogisticsNew()
    {
        if (isset($this->param['com_name']) && $this->param['com_name']) {
            $this->apiSuccess(Db::name('kuaidi')->whereLike('kuaidiname', '%' . $this->param['com_name'] . '%')->order('kuaidi_id asc')->field('kuaidiname com_name,kuaidicom com_id')->select());
        } elseif (isset($this->param['com_id']) && $this->param['com_id']) {
            $this->apiSuccess(Db::name('kuaidi')->whereLike('kuaidicom', '%' . $this->param['com_id'] . '%')->order('kuaidi_id asc')->field('kuaidiname com_name,kuaidicom com_id')->select());
        } else {
            $this->apiSuccess(Db::name('kuaidi')->order('kuaidi_id asc')->field('kuaidiname com_name,kuaidicom com_id')->select());
        }
    }

    /**
     * Title("获取发货城市信息")
     * @param("token","必填")
     */
    public function getCity()
    {
        $json_str = file_get_contents('./static/js/jqcity/allcity.js');
        $json_str = str_replace('callback(', '', $json_str);
        $json_str = str_replace(');', '', $json_str);
        $json_arr = json_decode($json_str, true);
        $result = [];
        $result['province'] = $json_arr['province'];
        $result['city'] = $json_arr['city'];
        $this->apiSuccess($result);
    }

    /**
     * Title("申请发货")
     * @param ("token","必填")
     * @param ("order_no","订单号，必填")
     * @param ("company","物流公司，必填")
     * @param ("numbers","物流单号，必填")
     * @param ("phone","收件人手机号，顺丰速运和顺丰快运必填")
     * @param ("post_date","配送时间，必填，格式：yyyy-mm-dd")
     * @param ("delivery_date","预计送达时间，必填,格式：yyyy-mm-dd")
     * @param ("province_id","发货省份ID,必填")
     * @param ("city_id","发货城市ID,必填")
     */
    public function applyDelivery()
    {
        if (!isset($this->param['order_no'])) {
            $this->apiError('订单号错误');
        }
        if (!isset($this->param['company'])) {
            $this->apiError('物流公司错误');
        }
        if (!in_array($this->param['company'], $this->com)) {
            $this->apiError('未找到物流公司');
        }
        if (!isset($this->param['numbers']) || !$this->param['numbers']) {
            $this->apiError('物流单号错误');
        }
        if (in_array($this->param['company'], ['顺丰速运', '顺丰快运'])) {
            $pattern_phone = '/^1[3456789]\d{9}$/';
            if (!isset($this->param['phone']) || !preg_match($pattern_phone, $this->param['phone'])) {
                $this->apiError('收件人手机号错误');
            }
        }
        $pattern_date = '/^\d{4}-\d{2}-\d{2}$/';
        if (!isset($this->param['post_date']) || !preg_match($pattern_date, $this->param['post_date'])) {
            $this->apiError('配送时间错误');
        }
        if (!isset($this->param['delivery_date']) || !preg_match($pattern_date, $this->param['delivery_date'])) {
            $this->apiError('预计送达时间错误');
        }
        if (!isset($this->param['province_id']) || !$this->param['province_id']) {
            $this->apiError('发货省份ID错误');
        }
        if (!isset($this->param['city_id']) || !$this->param['city_id']) {
            $this->apiError('发货城市ID错误');
        }
        $order_info = Db::name('order')
            ->where('out_order_no', $this->param['order_no'])
            ->field('order_no,out_order_no,supplier_id,gys_fh_state,supplier_state')
            ->find();
        if ($order_info) {
            if ($order_info['supplier_id'] != $this->member_id) {
                $this->apiError('无订单权限');
            }
            if ($order_info['supplier_state'] != 1) {
                $this->apiError('等待确认订单');
            }
            if ($order_info['gys_fh_state'] == 1) {
                $this->apiError('订单无需多次发货');
            }
            $param = [];
            $param['order_no'] = $order_info['order_no'];
            $param['event'] = 'edit_fahuo_gys';
            $param['wuliu'] = $this->param['company'];
            $param['sjrsjh'] = $this->param['phone'];
            $param['wuliudanhao'] = $this->param['numbers'];
            $param['post_date'] = $this->param['post_date'];
            $param['delivery_date'] = $this->param['delivery_date'];
            $param['province2'] = $this->param['province_id'];
            $param['city2'] = $this->param['city_id'];
            $param['yanchi'] = 'no';
            $orderdb = new Orderdb();
            $orderdb->param = $param;
            $return = $orderdb->editOrder();
            if ($return == 'success') {
                $result = [];
                $result['order_no'] = $this->param['order_no'];
                $this->apiSuccess($result);
            } else {
                $this->apiError($return);
            }
            $this->apiSuccess($return);
        } else {
            $this->apiError('未找到订单号');
        }

    }

    /**
     * Title("申请发货")
     * @param ("token","必填")
     * @param ("order_no","订单号，必填")
     * @param ("company","物流公司，必填")
     * @param ("numbers","物流单号，必填")
     * @param ("phone","收件人手机号，顺丰速运和顺丰快运必填")
     * @param ("post_date","配送时间，必填，格式：yyyy-mm-dd")
     * @param ("delivery_date","预计送达时间，必填,格式：yyyy-mm-dd")
     * @param ("province_id","发货省份ID,必填")
     * @param ("city_id","发货城市ID,必填")
     */
    public function applyDeliveryNew()
    {
        if (!isset($this->param['order_no'])) {
            $this->apiError('订单号错误');
        }
        if (!isset($this->param['company'])) {
            $this->apiError('物流公司错误');
        }
        $get_com_count = Db::name('kuaidi')->where('kuaidiname', $this->param['company'])->count();
        if ($get_com_count == 0) {
            $this->apiError('未找到物流公司');
        }
        if (!isset($this->param['numbers']) || !$this->param['numbers']) {
            $this->apiError('物流单号错误');
        }
        if (in_array($this->param['company'], ['顺丰速运', '顺丰快运'])) {
            $pattern_phone = '/^1[3456789]\d{9}$/';
            if (!isset($this->param['phone']) || !preg_match($pattern_phone, $this->param['phone'])) {
                $this->apiError('收件人手机号错误');
            }
        }
        $pattern_date = '/^\d{4}-\d{2}-\d{2}$/';
        if (!isset($this->param['post_date']) || !preg_match($pattern_date, $this->param['post_date'])) {
            $this->apiError('配送时间错误');
        }
        if (!isset($this->param['delivery_date']) || !preg_match($pattern_date, $this->param['delivery_date'])) {
            $this->apiError('预计送达时间错误');
        }
        if (!isset($this->param['province_id']) || !$this->param['province_id']) {
            $this->apiError('发货省份ID错误');
        }
        if (!isset($this->param['city_id']) || !$this->param['city_id']) {
            $this->apiError('发货城市ID错误');
        }
        $order_info = Db::name('order')
            ->where('out_order_no', $this->param['order_no'])
            ->field('order_no,out_order_no,supplier_id,gys_fh_state,supplier_state')
            ->find();
        if ($order_info) {
            if ($order_info['supplier_id'] != $this->member_id) {
                $this->apiError('无订单权限');
            }
            if ($order_info['supplier_state'] != 1) {
                $this->apiError('等待确认订单');
            }
            if ($order_info['gys_fh_state'] == 1) {
                $this->apiError('订单无需多次发货');
            }
            $param = [];
            $param['order_no'] = $order_info['order_no'];
            $param['event'] = 'edit_fahuo_gys';
            $param['wuliu'] = $this->param['company'];
            $param['sjrsjh'] = $this->param['phone'];
            $param['wuliudanhao'] = $this->param['numbers'];
            $param['post_date'] = $this->param['post_date'];
            $param['delivery_date'] = $this->param['delivery_date'];
            $param['province2'] = $this->param['province_id'];
            $param['city2'] = $this->param['city_id'];
            $param['yanchi'] = 'no';
            $orderdb = new Orderdb();
            $orderdb->param = $param;
            $return = $orderdb->editOrder();
            if ($return == 'success') {
                $result = [];
                $result['order_no'] = $this->param['order_no'];
                $this->apiSuccess($result);
            } else {
                $this->apiError($return);
            }
            $this->apiSuccess($return);
        } else {
            $this->apiError('未找到订单号');
        }

    }

    /**
     * Title("消息队列")
     * @param ("token","必填")
     */
    public function msgList()
    {
        $msgdb = new TljMsgdb();
        $get_msg = $msgdb
            ->where('member_id', $this->member_id)
            ->where('is_read', 0)
            ->field('id msg_id,msg_type,msg_param')
            ->order('id asc')
            ->find();
        $no_read_count = $msgdb
            ->where('member_id', $this->member_id)
            ->where('is_read', 0)
            ->count();
        $result = [];
        $result['unread_msg_num'] = $no_read_count;
        if ($get_msg) {
            $result['msg_info'] = $get_msg;
        } else {
            $arr = [];
            $result['msg_info'] = (object)$arr;
        }
        $this->apiSuccess($result);
    }

    /**
     * Title("处理未读消息")
     * @param ("token","必填")
     * @param ("msg_id","消息ID，必填")
     */
    public function handelMsg()
    {
        if (!isset($this->param['msg_id'])) {
            $this->apiError('msg_id错误');
        }
        $msgdb = new TljMsgdb();
        $get_msg = $msgdb->find($this->param['msg_id']);
        if ($get_msg) {
            if ($get_msg['member_id'] != $this->member_id) {
                $this->apiError('没有操作权限');
            } else {
                $get_msg->save(['is_read' => 1]);
                $this->apiSuccess(array('msg_id' => $this->param['msg_id']));
            }
        } else {
            $this->apiError('未找到消息');
        }
    }

    /**
     * Title("申请收货")
     * @param("order_no"，“必填，订单号”)
     * @param("signer","必填，签收人")
     */
    public function applyReceive()
    {
        if (!isset($this->param['order_no'])) {
            $this->apiError('订单号错误');
        }
        if (!isset($this->param['signer'])) {
            $this->apiError('签收人错误');
        }
        $order_info = Db::name('order')
            ->where('out_order_no', $this->param['order_no'])
            ->field('order_no,out_order_no,supplier_id,gys_fh_state,gys_sh_state')
            ->find();
        if ($order_info) {
            if ($order_info['supplier_id'] != $this->member_id) {
                $this->apiError('无订单权限');
            }
            if ($order_info['gys_fh_state'] == 2) {
                $this->apiError('订单尚未发货');
            }
            if ($order_info['gys_sh_state'] == 1) {
                $this->apiError('无需多次收货');
            }
            $param = [];
            $param['order_no'] = $order_info['order_no'];
            $param['event'] = 'edit_shouhuo_gys';
            $param['post_data']['qianshouyuan'] = $this->param['signer'];
            $orderdb = new Orderdb();
            $orderdb->param = $param;
            $return = $orderdb->editOrder();
            if ($return == '保存成功') {
                $result = [];
                $result['order_no'] = $this->param['order_no'];
                $this->apiSuccess($result);
            } else {
                $this->apiError($return);
            }
            $this->apiSuccess($return);
        } else {
            $this->apiError('未找到订单号');
        }
    }

    /**
     * Title("上传采购发票并提交审核")
     * @param("order_no","必填，订单号")
     * @param("invoice_info_arr","必填，发票信息数组")
     * @param("invoice_info_arr.invoice_duty","必填，发票编号")
     * @param("invoice_info_arr.invoice_file","必填，发票凭证")
     */
    public function applyInvoice()
    {
        if (!isset($this->param['order_no'])) {
            $this->apiError('订单号错误');
        }
        if (!isset($this->param['invoice_info_arr'])) {
            $this->apiError('发票信息错误');
        }
        if (!is_array($this->param['invoice_info_arr'])) {
            $this->apiError('发票信息数组错误');
        }
        if (count($this->param['invoice_info_arr']) == 0) {
            $this->apiError('发票信息数组错误');
        }
        $order_param = [];
        $order_param['event'] = 'caigou_invoice';
        $order_param['caigou_state'] = 2;
        $order_param['caigou_invoice_index'] = count($this->param['invoice_info_arr']);
        $caigou_invoice_duty = [];
        $caigou_invoice_pz = [];
        // 校验错误
        foreach ($this->param['invoice_info_arr'] as $key => $val) {
            if (!isset($val['invoice_duty']) || !$val['invoice_duty']) {
                $this->apiError('发票信息编号错误');
            }
            if (!isset($val['invoice_file']) || !$val['invoice_file']) {
                $this->apiError('发票信息凭证错误');
            }
            array_push($caigou_invoice_duty, $val['invoice_duty']);
            array_push($caigou_invoice_pz, $val['invoice_file']);
        }
        $get_order = Db::name('Order')
            ->where('out_order_no', $this->param['order_no'])
            ->field('order_no,out_order_no,caigou_state,supplier_id')
            ->find();
        if ($get_order) {
            if ($get_order['supplier_id'] != $this->member_id) {
                $this->apiError('订单无权限');
            }
            if (in_array($get_order['caigou_state'], [1, 5])) {
                $this->apiError('订单号【' . $val['out_order_no'] . '】发票已审核');
            }
            $order_param['order_no'] = $get_order['order_no'];
            $order_param['caigou_invoice_duty'] = implode(',', $caigou_invoice_duty);
            $order_param['caigou_invoice_pz'] = implode(',', $caigou_invoice_pz);
            $orderdb = new Orderdb();
            $orderdb->param = $order_param;
            $orderdb->editOrder();
            $this->apiSuccess(array('order_no' => $this->param['order_no']));
        } else {
            $this->apiError('订单信息错误');
        }
    }

    /**
     * Title("商品报价")
     * @param("quote_arr","报价信息")
     * @param("quote_arr.goods_sku","商品SKU")
     * @param("quote_arr.api_price","报价")
     * @param("quote_arr.cost_price","成本价")
     * @param("quote_arr.cycle_day","报价周期，3/4")
     * @param("quote_arr.area_type","报价区域类型：0全国，1非偏远地区，2偏远地区")
     * @param("quote_arr.faraway","偏远地区省份")
     * @param("quote_arr.real_stock","真实库存")
     */
    public function goodsQuote()
    {
        $this->apiError('暂时关闭');
        if (!isset($this->param['quote_arr'])) {
            $this->apiError('报价信息错误');
        }
        if (!is_array($this->param['quote_arr'])) {
            $this->apiError('报价信息错误');
        }
        if (count($this->param['quote_arr']) == 0) {
            $this->apiError('报价信息错误');
        }

        $pianyuan = Db::name('site_config')->where('config_name', 'PIANYUAN')->value('config_value');
        $pianyuan_arr = explode(',', str_replace("\n", ',', $pianyuan));

        $quote_arr_new = $this->param['quote_arr'];
        foreach ($this->param['quote_arr'] as $k => $quote_arr) {
            if (!isset($quote_arr['goods_sku'])) {
                $this->apiError('报价商品错误');
            }
            if (!isset($quote_arr['api_price'])) {
                $this->apiError('报价错误');
            }
            if (!isset($quote_arr['cost_price'])) {
                $this->apiError('成本价错误');
            }
            if (!isset($quote_arr['cycle_day'])) {
                $this->apiError('报价周期错误');
            }
            if (!in_array($quote_arr['cycle_day'], [3, 4])) {
                $this->apiError('报价周期错误');
            }
            if (!isset($quote_arr['area_type'])) {
                $this->apiError('报价区域类型错误');
            }
            if (!in_array($quote_arr['area_type'], [0, 1, 2])) {
                $this->apiError('报价区域类型错误');
            }
            if ($quote_arr['area_type'] == 2) {
                if (!isset($quote_arr['faraway'])) {
                    $this->apiError('偏远地区省份错误1');
                }
                if (!is_array($quote_arr['faraway'])) {
                    $this->apiError('偏远地区省份错误2');
                }
                if (count($quote_arr['faraway']) == 0) {
                    $this->apiError('偏远地区省份错误3');
                }
                foreach ($quote_arr['faraway'] as $key => $val) {
                    if (!in_array($val, $pianyuan_arr)) {
                        $this->apiError('偏远地区省份错误4');
                    }
                }
            }
            if (!isset($quote_arr['real_stock'])) {
                $this->apiError('真实库存错误');
            }
            if ($quote_arr['real_stock'] < 1) {
                $this->apiError('真实库存错误');
            }
            $get_goods = Db::name("goods")->field('goods_id,goods_sku,check_area,goods_name,is_lock,jun_id')->where('goods_sku', $quote_arr['goods_sku'])->find();
            if (!$get_goods) {
                $this->apiError('商品编号[' . $quote_arr['goods_sku'] . ']错误');
            }
            if ($get_goods['is_lock'] == 1) {
                $this->apiError('商品编号[' . $quote_arr['goods_sku'] . ']已被锁定');
            }
            $get_price = Db::name('sale_price')->where('goods_sku', $quote_arr['goods_sku'])->order('sale_price_id desc')->find();
            if (!$get_price) {
                $this->apiError('商品编号[' . $quote_arr['goods_sku'] . ']价格错误');
            }
            if ($quote_arr['api_price'] / $get_price['sale_price'] <= 0.55 || $quote_arr['api_price'] / $get_price['sale_price'] >= 0.99) {
                $this->apiError('商品编号[' . $quote_arr['goods_sku'] . ']折扣率须在55%到99%之间');
            }
            $get_baojia = Db::name('baojia')->where('goods_id', $get_goods['goods_id'])->order('baojia_id desc')->value('create_time');
            if ($get_baojia) {
                if (date('Y-m-d', $get_baojia) == date('Y-m-d')) {
                    $this->apiError('商品编号[' . $quote_arr['goods_sku'] . ']同一天报价或下架');
                }
            }
            $quote_arr_new[$k]['jun_id'] = $get_goods['jun_id'];
            $quote_arr_new[$k]['goods_id'] = $get_goods['goods_id'];
            $quote_arr_new[$k]['goods_name'] = $get_goods['goods_name'];
            $quote_arr_new[$k]['sale_price'] = $get_price['sale_price'];
            $quote_arr_new[$k]['caigoujia'] = $get_price['caigoujia'];
            $quote_arr_new[$k]['chengbenjia'] = $get_price['chengbenjia'];
            $quote_arr_new[$k]['beizhu'] = $get_price['beizhu'];
        }

        // 开始保存数据
        $view_stock_arr = 4;
        $audit_flag = 2;
        $baojia_data = [];
        $goods_sku_arr = [];
        $goodsdb = new Goodsdb();
        $saledb = new SalePricedb();
        foreach ($quote_arr_new as $key => $val) {
            // 保存商品
            $data_goods = [];
            $data_goods['view_stock'] = $view_stock_arr;
            $data_goods['audit_goods'] = $view_stock_arr;
            $data_goods['zhenshi'] = $val['real_stock'];
            $data_goods['down_time'] = time() + $val['cycle_day'] * 86400;
            $data_goods['diqu'] = $val['area_type'];
            $data_goods['shengfen'] = implode(',', $val['faraway']);
            $get_goods = $goodsdb->where('goods_sku', $val['goods_sku'])->find();
            $get_goods->save($data_goods);

            // 保存商品价格和库存
            $get_sale = $saledb->where('site_id', SITE_ID)->where('goods_sku', $get_goods['goods_sku'])->order('sale_price_id desc')->find();
            $get_sale->save(['api_price' => $val['api_price'], 'view_stock' => $view_stock_arr]);

            // 保存报价表
            $save_baojia = [];
            $save_baojia ['zhenshi'] = $val['real_stock'];
            $save_baojia ['diqu'] = $val['area_type'];
            $save_baojia ['shengfen'] = $data_goods['shengfen'];
            $save_baojia ['goods_id'] = $val['goods_id'];
            $save_baojia ['baojia'] = $val['api_price'];
            $save_baojia ['kucun'] = $view_stock_arr;
            $save_baojia ['apply_member_id'] = $this->member_id;
            $save_baojia ['audit_state'] = $audit_flag;
            $save_baojia ['goods_type'] = strstr($val['goods_sku'], 'SKU') ? '自选库' : '重点库';
            $save_baojia['goods_sku'] = $val['goods_sku'];
            $save_baojia['goods_shuzi'] = $val['jun_id'];
            $save_baojia['goods_name'] = $val['goods_name'];
            $save_baojia['cankao'] = $val['sale_price'];
            $save_baojia['caigoujia'] = $val['caigoujia'];
            $save_baojia['beizhu1'] = $val['chengbenjia'];
            $save_baojia['beizhu2'] = $val['beizhu'];
            $save_baojia['chengben'] = $val['cost_price'] ?: $val['api_price'];
            $save_baojia['lilv'] = ($save_baojia ['baojia'] - $save_baojia['chengben']) / $save_baojia['baojia'];
            $save_baojia['lilv2'] = ($save_baojia ['cankao'] - $save_baojia['baojia']) / $save_baojia['cankao'];
            $save_baojia['beizhu'] = '';
            $save_baojia['zhouqi'] = time() + $val['cycle_day'] * 86400;

            if ((floatval(abs($save_baojia['lilv2'])) <= 0.15) || (floatval(abs($save_baojia['lilv2'])) > 0.15 && floatval(abs($save_baojia['lilv2'])) <= 0.3 && floatval(abs($save_baojia['lilv'])) >= 0.1 && floatval(abs($save_baojia['lilv'])) <= 0.5)) {
                // if (floatval(abs($temp['lilv2'])) <= 0.15) {
                $save_baojia['audit_state'] = 1;
                $save_baojia['audit_member_id'] = $this->member_id;
                $save_baojia['audit_time'] = time();
                //  $temp['beizhu'] = $temp['beizhu'] . '__低于15%自动审核';
                // 推送军采
                $junapi = new Api();
                if ($save_baojia['goods_type'] == '重点库') {
                    $post_jun['priceList'] = array();
                    $price_list_arr['sku'] = $save_baojia['goods_sku'];
                    $price_list_arr['stock'] = $save_baojia['kucun'];
                    $price_list_arr['price'] = $save_baojia['baojia'];
                    $price_list_arr['linkurl'] = 'http://tailongjipc.dixintong.com/goods_detail.html?goods_sku=' . $val['goods_id'];
                    $price_list_arr['eccode'] = $val['goods_id'];
                    $price_list_arr['linkprice'] = $save_baojia['baojia'];
                    array_push($post_jun['priceList'], $price_list_arr);
                    $junapi->ajaxCountPrice($post_jun);
                } else {
                    $data = array();
                    $temp1 ['sku'] = $val['goods_sku'];
                    $temp1 ['updateType'] = 6;
                    array_push($data, $temp1);
                    $junapi->ajaxproductupdateinfo($data);
                }


            }
            array_push($baojia_data, $save_baojia);
            array_push($goods_sku_arr, $val['goods_sku']);

        }
        $baojiadb = new Baojiadb();
        if (count($baojia_data)) {
            $baojiadb->saveAll($baojia_data);
        }
        $this->apiSuccess(['goods_sku_arr' => $goods_sku_arr]);
    }

    /**
     * Title("获取偏远地区")
     */
    public function getFaraway()
    {
        $pianyuan = Db::name('site_config')->where('config_name', 'PIANYUAN')->value('config_value');
        $pianyuan_arr = str_replace("\n", ',', $pianyuan);
        $this->apiSuccess(explode(',', $pianyuan_arr));
    }

    /**
     * Title("商品增量信息")
     * param("date","必填,格式 整天查询：2024-01-01；整点查询：2014-01-01 09")
     */
    public function goodsInc()
    {
        if (!isset($this->param['date'])) {
            $this->apiError('日期错误');
        }
        if (!in_array(strlen($this->param['date']), [10, 13])) {
            $this->apiError('日期格式错误');
        }
        $data = Db::name('callet_log')->whereLike('callet_date', $this->param['date'] . '%')->order('callet_date asc')->field('goods_sku,callet_date date')->select();
        $this->apiSuccess($data);
    }

    /**
     * Title("确认订单")
     * param ("order_no","订单号,必填")
     * param ("huikuandanwei","汇款单位")
     */
    public function confirmOrder()
    {
        if (!isset($this->param['order_no'])) {
            $this->apiError('订单号错误');
        }
        if (!isset($this->param['huikuandanwei'])) {
            $this->apiError('汇款单位错误');
        }
        $get_order = Db::name('order')->where('out_order_no', $this->param['order_no'])->field('order_id,out_order_no,order_no,supplier_state,supplier_id')->find();
        if (!$get_order) {
            $this->apiError('订单错误');
        }
        if ($get_order['supplier_id'] != $this->member_id) {
            $this->apiError('订单无权限');
        }
        if ($get_order['supplier_state'] == 1) {
            $this->apiError('无需多次确认订单');
        }
        $data ['supplier_state'] = 1;
        $data ['huikuandanwei'] = $this->param['huikuandanwei'];
        $data ['xsht'] = '生成中';
        $data ['cght'] = '生成中';
        $data ['shd'] = '生成中';
        $data ['xsfp'] = '生成中';
        $data ['cgfp'] = '生成中';
        //$data ['ysd'] = '生成中';
        $data['supplier_confirm_time'] = time();
        $orderdb = new Orderdb();
        $orderdb->save($data, [
            'order_no' => $get_order['order_no']
        ]);
        $tpl [0] ['buildtpl_type'] = 'xsht';
        $tpl [0] ['order_no'] = $get_order['order_no'];
        $tpl [1] ['buildtpl_type'] = 'cght';
        $tpl [1] ['order_no'] = $get_order['order_no'];
        $tpl [2] ['buildtpl_type'] = 'shd';
        $tpl [2] ['order_no'] = $get_order['order_no'];
        $tpl [3] ['buildtpl_type'] = 'xsfp';
        $tpl [3] ['order_no'] = $get_order['order_no'];
        $tpl [4] ['buildtpl_type'] = 'cgfp';
        $tpl [4] ['order_no'] = $get_order['order_no'];
        /*$tpl [5] ['buildtpl_type'] = 'ysd';
        $tpl [5] ['order_no'] = $get_order['order_no'];*/
        $buildtpldb = new Buildtpldb();
        $buildtpldb->saveAll($tpl);
        // 日志流转
        $order_logdb = new OrderLogdb();
        $order_logdb->param = array(
            'type_index' => 3,
            'order_no' => $get_order['order_no'],
            'member_id' => $this->member_id,
            'view_text' => '已确认订单',
            'post_json' => $this->param
        );
        $order_logdb->saveData();
        $this->apiSuccess(array('order_no' => $this->param['order_no'], 'supplier_state' => 1));
    }

    /**
     * Title("获取商品电子发票默认值")
     * param("goods_sku_arr","必填，商品编号数组")
     */
    public function getGoodsEInvoice()
    {
        if (!isset($this->param['goods_sku_arr'])) {
            $this->apiError('商品编号数组错误');
        }
        $data = Db::name('goods')->whereIn('goods_sku', $this->param['goods_sku_arr'])
            ->field('goods_sku,product_area swdl,shuiwu_id swbm,product_firm kpmc,invoice_model ggxh,goods_unit dw')
            ->select();
        $this->apiSuccess($data);
    }

    /**
     * Title("申请电子发票")
     * param("order_no","必填,订单号")
     * param("invoice_arr","必填，发票信息，数组")
     * param("...goods_sku","必填，商品SKU")
     * param("...swdl","必填，税务大类")
     * param("...swbm","必填，税务编码，19位")
     * param("...kpmc","必填,开票名称")
     * param("...ggxh","必填,规格型号")
     * param("...dw","必填,单位")
     */
    public function applyEInvoice()
    {
        if (!isset($this->param['order_no'])) {
            $this->apiError('订单号错误');
        }
        if (!isset($this->param['invoice_arr'])) {
            $this->apiError('发票信息错误');
        }
        $get_order = Db::name('order')->where('out_order_no', $this->param['order_no'])->field('order_no,supplier_id,gys_fh_state,apply_state')->find();
        if (!$get_order) {
            $this->apiError('订单信息错误');
        }
        if (in_array($get_order['apply_state'],[2,3])) {
            $this->apiError('发票状态：'.$get_order['apply_state'].'；不能再次申请');
        }
        if ($get_order['gys_fh_state'] != 1) {
            $this->apiError('发货后才能申请电子发票');
        }
        /*if ($get_order['supplier_id'] != $this->member_id) {
            $this->apiError('订单无权限');
        }*/
        $cartdb = new Cartdb();
        $get_cart = $cartdb->with(['goods'])->where('order_no', $get_order['order_no'])->select();
        if ($get_cart->isEmpty()) {
            $this->apiError('订单商品信息错误');
        }
        if (count($get_cart) != count($this->param['invoice_arr'])) {
            $this->apiError('发票信息和订单商品不匹配');
        }
        //校验
        foreach ($this->param['invoice_arr'] as $key => $val) {
            if (!isset($val['goods_sku']) || !$val['goods_sku']) {
                $this->apiError('商品SKU错误');
            }
            if (!isset($val['swdl']) || !$val['swdl']) {
                $this->apiError('税务大类错误');
            }
            if (!isset($val['swbm']) || !$val['swbm']) {
                $this->apiError('税务编码错误');
            }
            if (strlen($val['swbm']) != 19) {
                $this->apiError('税务编码需为19位数');
            }
            if (!isset($val['kpmc']) || !$val['kpmc']) {
                $this->apiError('开票名称错误');
            }
            if (!isset($val['ggxh']) || !$val['ggxh']) {
                $this->apiError('规格型号错误');
            }
            if (!isset($val['dw']) || !$val['dw']) {
                $this->apiError('单位错误');
            }
        }
        $is_change = 0;
        $num = 0;
        $update = [];
        foreach ($get_cart as $key => $val) {
            foreach ($this->param['invoice_arr'] as $k => $v) {
                if ($val['goods_sku'] == $v['goods_sku']) {
                    $num++;
                    if ($val['goods']['product_area'] != $v['swdl']) {
                        $is_change = 1;
                    }
                    if ($val['goods']['shuiwu_id'] != $v['swbm']) {
                        $is_change = 1;
                    }
                    if ($val['goods']['product_firm'] != $v['kpmc']) {
                        $is_change = 1;
                    }
                    if ($val['goods']['invoice_model'] != $v['ggxh']) {
                        $is_change = 1;
                    }
                    if ($val['goods']['goods_unit'] != $v['dw']) {
                        $is_change = 1;
                    }
                    $update_data = [];
                    $update_data['product_area'] = $v['swdl'];
                    $update_data['shuiwu_id'] = $v['swbm'];
                    $update_data['product_firm'] = $v['kpmc'];
                    $update_data['invoice_model'] = $v['ggxh'];
                    $update_data['goods_unit'] = $v['dw'];
                    $update_data['apply_state'] = 2;
                    $update_data['nopass_info'] = '';
                    $update_data['cart_id'] = $val['cart_id'];
                    array_push($update, $update_data);
                }
            }
        }
        if($num != count($get_cart)){
            $this->apiError('订单商品没找到对应的发票信息');
        }
        $cartdb->saveAll($update);
        $ucartdb = new UCartdb();
        $ucartdb->saveAll($update);
        // 保存日志
        $save_apply['order_no'] = $this->param['order_no'];
        $save_apply['admin_id'] = $this->member_id;
        $save_apply['log'] = '申请电子发票';
        $log = new OrderApplyEinvoicedb();
        $log->save($save_apply);
        $ulog = new UOrderApplyEinvoicedb();
        $ulog->save($save_apply);
        // 保存订单信息
        $save_order = [];
        $save_order['apply_state'] = 2;
        $save_order['apply_time'] = time();
        $save_order['is_change'] = $is_change;
        $orderdb = new Orderdb();
        $j_order = $orderdb->where('out_order_no',$this->param['order_no'])->find();
        $j_order->save($save_order);
        $uorderdb = new UOrderdb();
        $u_order = $uorderdb->where('out_order_no',$this->param['order_no'])->find();
        $u_order->save($save_order);
        $this->apiSuccess(array('order_no' => $this->param['order_no'], 'apply_state' => 2));
    }
}